<?php $this->pageTitle=Yii::app()->name . ' - '.UserModule::t("Profil");
$this->breadcrumbs=array(
        UserModule::t("Profil")=>array('profile'),
        UserModule::t("Edytuj"),
);
?><h2><?php echo UserModule::t('Edit profile'); ?></h2>
<?php echo $this->renderPartial('menu'); ?>

<?php if(Yii::app()->user->hasFlash('profileMessage')): ?>
<div class="success">
<?php echo Yii::app()->user->getFlash('profileMessage'); ?>
</div>
<?php endif; ?>
<div class="form">
<?php $form=$this->beginWidget('UActiveForm', array(
    'id'=>'profile-form',
    'enableAjaxValidation'=>true,
    'htmlOptions' => array('enctype'=>'application/x-www-form-urlencoded'),
)); ?>

    <p class="note"><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></p>

    <?php echo $form->errorSummary(array($model,$profile));
        $profileFields=$profile->getFields();
        if ($profileFields) {
            foreach($profileFields as $field) {
                if ($field->varname=="parameters")
                    echo $form->hiddenField($profile,$field->varname,array('maxlength'=>(($field->field_size)?$field->field_size:255)));
                else if ($field->varname=="news_locations")
                    echo $form->hiddenField($profile,$field->varname,array('maxlength'=>(($field->field_size)?$field->field_size:255)));
                else if ($field->varname=="favourites")
                    echo $form->hiddenField($profile,$field->varname,array('maxlength'=>(($field->field_size)?$field->field_size:255)));
                else {
            ?>
        <div class="row">
            <div class="row profile_label"><?php echo $form->labelEx($profile,$field->varname);
            ?></div><div class="row profile_input"><?php
            if ($field->widgetEdit($profile)) {
                echo $field->widgetEdit($profile);
            } elseif ($field->range) {
                echo $form->dropDownList($profile,$field->varname,Profile::range($field->range));
            } elseif ($field->field_type=="TEXT") {
                echo $form->textArea($profile,$field->varname,array('rows'=>6, 'cols'=>50));
            } else {
                echo $form->textField($profile,$field->varname,array('size'=>20,'maxlength'=>(($field->field_size)?$field->field_size:255)));
            }
            echo $form->error($profile,$field->varname); ?>
            </div>
        </div>  
            	<?php
                }
            }
        }
?>
        <div class="row">
            <div class="row profile_label"><?php echo $form->labelEx($model,'username'); ?></div>
            <div class="row profile_input"><?php echo $form->textField($model,'username',array('size'=>20,'maxlength'=>20, 'readonly'=>'readonly')); ?></div>
            <?php echo $form->error($model,'username'); ?>
        </div>

        <div class="row">
            <div class="row profile_label"><?php echo $form->labelEx($model,'email'); ?></div>
            <div class="row profile_input"><?php echo $form->textField($model,'email',array('size'=>20,'maxlength'=>128, 'readonly'=>'readonly')); ?></div>
            <?php echo $form->error($model,'email'); ?>
        </div>

        <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery/jquery.ui.datepicker.js" type="text/javascript"></script>
		<script>
			$(function() {
				$( "#Profile_birthday" ).datepicker({
					changeMonth: true,
					changeYear: true,
					dateFormat: 'yy-mm-dd',
					yearRange: '1900:2011'
				});
			});
		</script>
        <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery/jquery.ui.core.js" type="text/javascript"></script>
        <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery/jquery.ui.widget.js" type="text/javascript"></script>
        <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery/jquery.ui.mouse.js" type="text/javascript"></script>
        <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery/jquery.ui.draggable.js" type="text/javascript"></script>
        <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery/jquery.ui.droppable.js" type="text/javascript"></script>
        <script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery/jquery_favs_newsletter.js" type="text/javascript"></script>
        
        <link rel="stylesheet" href="<?php echo Yii::app()->request->baseUrl; ?>/css/jquery-ui-1.8.16.custom.css" type="text/css" />

<?php
    $tmp=splitParametersFromValues();
    $parameters=$tmp[0];
    $allParams=$tmp[1];
    $allValues=$tmp[2];
    $splittedParams=splitString($allParams);
    $splittedValues=splitString($allValues);
?>
		<div class="params_description">
		    W celu zapisania się do listy subskrypcyjnej należy w panelach po prawej stronie (wybrane parametry i wybrane miejsca) posiadać przynajmniej po jednej opcji. Mail zawiera wybrane parametry (których wartości można określić z dołu wpisując je w pola przy nazwie parametru) dla wszystkich miast, które dodaliśmy do listy. Oprócz tego, podana jest data wraz z godziną, o której przewidywana jest dana pogoda. Wszystki parametry i miejsca można przeciągać na wysokości swojego poziomu pomiędzy każdym kontenerem (gdzie można opcję upuścić podświetla się na żółto). Każdy parametr, który ma zawierać część po przecinku musi być zapisany z kropką, a nie przecinkiem. W celu zakończenia edycji newslettera jak i pól profilu, należy na dole nacisnąć przycisk "zapisz".
		</div>
        <div class="demo ui-widget ui-helper-clearfix" id="favs_newsletter">
        <div id="products" style="display: inline-block;" class="params_container ui-widget-content ui-state-default">
            <h3 class="ui-widget-header">Dostępne parametry</h3>
            <ul id="parameters" class="parameters ui-helper-reset ui-helper-clearfix">
                <?php
                    $all='skin_temp,soil_temp,visibility,u_wind_10m,v_wind_10m,total_col_rain,total_col_snow,surf_rel_hum,low_cloud_fra,mid_cloud_fra,high_cloud_fra,';
                    $allAvailableParams=explode(',', substr($all, 0, -1));
                    for ($i=0; $i<sizeof($allAvailableParams); $i++) {
                        $pos = stripos($allParams, $allAvailableParams[$i]);
                        if ($pos === false) {
                            if ($allAvailableParams[$i]=='v_wind_10m' || $allAvailableParams[$i]=='u_wind_10m') {
                                echo '<li class="ui-widget-content ui-corner-tr" id="u_wind_10m">';
                                $i++;
                            }
                            else
                                echo '<li class="ui-widget-content ui-corner-tr" id="'.$allAvailableParams[$i].'">';
                            echo '<span class="span_draggable">'.replaceName($allAvailableParams[$i]).'</span>';
                            echo '<br /><div class="input_not_draggable"><input size="4" onkeydown="changeValueOnKeyDown(this);" onkeyup="changeValueOnKeyUp(this);" type="text" name="value_'.$allAvailableParams[$i].'" id="value_'.$allAvailableParams[$i].'" />'.changeUnits($allAvailableParams[$i]).'</div>';
                            echo '</li>';
                        }
                    }
                ?>
            </ul>
        </div>
        <div id="favourites" class="params_container ui-widget-content ui-state-default">
            <h3 class="ui-widget-header" style="width: 390px;">Wybrane parametry</h3>
            <ul id="favourites_ul" class='parameters ui-helper-reset ui-helper-clearfix'>
            	<?php
                    for ($i=0; $i<sizeof($splittedParams); $i++) {
                        if ($splittedParams[$i]=='u_wind_10m') {
                            echo '<li class="ui-widget-content ui-corner-tr" id="u_wind_10m">';
                            echo '<span class="span_draggable">'.replaceName($splittedParams[$i]).'</span>';
                            echo '<br /><div class="input_not_draggable"><input size="4" onkeydown="changeValueOnKeyDown(this);" onkeyup="changeValueOnKeyUp(this);" type="text" value="'.$parameters[$splittedParams[$i]].'" name="value_'.$splittedParams[$i].'" id="value_'.$splittedParams[$i].'" />'.changeUnits($splittedParams[$i]).'</div>';
                            $i++;
                        }
                        else if ($splittedParams[$i]=='')
                            continue;
                        else {
                            echo '<li class="ui-widget-content ui-corner-tr" id="'.$splittedParams[$i].'">';
                            echo '<span class="span_draggable">'.replaceName($splittedParams[$i]).'</span>';
                            if ($splittedParams[$i]=='skin_temp' || $splittedParams[$i]=='soil_temp') {
                                $temp=$parameters[$splittedParams[$i]]-273.15;
                                echo '<br /><div class="input_not_draggable"><input size="4" type="text" value="'.$temp.'" name="value_'.$splittedParams[$i].'" id="value_'.$splittedParams[$i].'" />'.changeUnits($splittedParams[$i]).'</div>';
                            }
                            else {
                                if ($splittedParams[$i]=='visibility')
                                    round($parameters[$splittedParams[$i]]/=1000,2);
                                echo '<br /><div class="input_not_draggable"><input size="4" onkeydown="changeValueOnKeyDown(this);" onkeyup="changeValueOnKeyUp(this);" type="text" value="'.$parameters[$splittedParams[$i]].'" name="value_'.$splittedParams[$i].'" id="value_'.$splittedParams[$i].'" />'.changeUnits($splittedParams[$i]).'</div>';
                            }
                        }
                        echo '</li>';
                    }
                ?>
             </ul>
        </div>
    </div>
    
    <div class="demo ui-widget ui-helper-clearfix" id="favs_newsletter2">
        <div id="products" style="display: inline-block;" class="params_container ui-widget-content ui-state-default">
            <h3 class="ui-widget-header">Dostępne miejsca</h3>
            <ul id="cities" class="cities ui-helper-reset ui-helper-clearfix" style="font-size: medium;">
                <?php
                	$locations=getLocations();
                    $allLocations=getAllLocations();
                    $all='';
                    if ($locations!='pusto')
                        for ($i=0; $i<sizeof($locations); $i++)
                            $all.=$locations[$i]['title'].',';
                    for ($i=0; $i<sizeof($allLocations); $i++) {
                        $pos = stripos($all, $allLocations[$i]['title']);
                        if ($pos === false) {
                            echo '<li class="ui-widget-content ui-corner-tr" id="'.$allLocations[$i]['id'].'">';
                            echo $allLocations[$i]['title'];
                            echo '</li>';
                        }
                    }
                ?>
            </ul>
        </div>
        <div id="favs_cities" class="params_container ui-widget-content ui-state-default">
            <h3 class="ui-widget-header" style="width: 390px;">Wybrane miejsca</h3>
            <ul id="favs_cities_ul" class='cities ui-helper-reset'>
                <?php
                    if ($locations!='pusto')
	                    for ($i=0; $i<sizeof($locations); $i++) {
	                        echo '<li class="ui-widget-content ui-corner-tr" id="'.$locations[$i]['id'].'">';
	                        echo $locations[$i]['title'];
	                        echo '</li>';
	                    }
                ?>
             </ul>
        </div>
    </div>

    <div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? UserModule::t('Create') : UserModule::t('Zapisz'), array('class'=>'profile_button')); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->
<br />

<?php
function getParameters(){
    $userObject = Yii::app()->getModule('user')->user();
    $id=$userObject->id;
    $sql='SELECT parameters FROM tbl_profiles WHERE user_id=:id';
    $connection=Yii::app()->db;
    $command=$connection->createCommand($sql);
    $command->bindParam(":id",$id,PDO::PARAM_INT);
    $rows=$command->queryAll();
    
    return $rows;
}

/*function splitParameters($data){
    return explode(',', substr($data[0]['parameters'], 0, -1));
}*/

function splitParametersFromValues(){
	$temp=getParameters();
    $parameters=splitString($temp[0]['parameters']);
    $allParameters='';
    $allValues='';
    $data = array();
    foreach($parameters as $parameter){
        $tmp=explode('=', $parameter);
        $allParameters.=$tmp[0].',';
        if (isset($tmp[1])) {
            $data[$tmp[0]] = $tmp[1];
            $allValues.=$tmp[1].',';
        }
    }
    return array($data,$allParameters,$allValues);
}

function getLocations(){
    $userObject = Yii::app()->getModule('user')->user();
    $id=$userObject->id;
    $sql='SELECT news_locations FROM tbl_profiles WHERE user_id=:id';
    $connection=Yii::app()->db;
    $command=$connection->createCommand($sql);
    $command->bindParam(":id",$id,PDO::PARAM_INT);
    $rows=$command->queryAll();
    
    if ($rows[0]['news_locations']=='')
        return 'pusto';
    else {
        $sql='SELECT id,title FROM location WHERE id IN ('.substr($rows[0]['news_locations'], 0, -1).')';
        $command=$connection->createCommand($sql);
        $rows=$command->queryAll();

        $data = array();
        foreach($rows as $row){
            array_push($data, $row);
        }

        return $data;
    }
}

function splitString($string){
    return explode(',', substr($string, 0, -1));
}

function getAllLocations(){
    $connection=Yii::app()->db;
    $sql='SELECT id,title FROM location';
    $command=$connection->createCommand($sql);
    $rows=$command->queryAll();
    
    return $rows;
}

function replaceName($name) {
    if ($name=='skin_temp')
        return 'Temperatura odczuwalna';
    else if ($name=='soil_temp')
        return 'Temperatura gleby';
    else if ($name=='visibility')
        return 'Widoczność';
    else if ($name=='u_wind_10m')
        return 'Prędkość i kierunek wiatru';
    else if ($name=='v_wind_10m')
        return 'Prędkość i kierunek wiatru';
    else if ($name=='total_col_rain')
        return 'Opady deszczu';
    else if ($name=='total_col_snow')
        return 'Opady śniegu';
    else if ($name=='surf_rel_hum')
        return 'Wilgotność';
    else if ($name=='low_cloud_fra')
        return 'Niski pułap chmur';
    else if ($name=='mid_cloud_fra')
        return 'Średni pułap chmur';
    else if ($name=='high_cloud_fra')
        return 'Wysoki pułap chmur';
    else return 'error';
}

function changeUnits ($param) {
	if (($param=='skin_temp') || ($param=='soil_temp'))
        return '&deg;C';
	else if ($param=='visibility')
        return 'km';
	else if (($param=='u_wind_10m') || ($param=='v_wind_10m'))
        return 'm/s';
	else if (($param=='total_col_rain') || ($param=='total_col_snow'))
        return 'mm';
	else if (($param=='surf_rel_hum') || ($param=='low_cloud_fra') || ($param=='mid_cloud_fra') || ($param=='high_cloud_fra'))
        return '%';
	else return '';
}

?>